import xml.dom.minidom as XmlDocument
from utils import model


def generate_xml_str(voice: model.VoiceModel) -> str:
    # 定义XML文档对象
    doc = XmlDocument.Document()
    # 创建根节点
    speak_xml = doc.createElement('speak')
    speak_xml.attributes["xmlns"] = "http://www.w3.org/2001/10/synthesis"
    speak_xml.attributes["xmlns:mstts"] = "http://www.w3.org/2001/mstts"
    speak_xml.attributes["xmlns:emo"] = "http://www.w3.org/2009/10/emotionml"
    speak_xml.attributes["version"] = "1.0"
    speak_xml.attributes["xml:lang"] = "en-US"
    doc.appendChild(speak_xml)

    # for voice in speak.voice:
    # 创建一个节点，命名为user
    voice_xml = doc.createElement('voice')
    # 将该节点设置为xUsers的子节点
    speak_xml.appendChild(voice_xml)
    # 给标签添加属性
    voice_xml.attributes['name'] = voice.voice
    # 创建一个新的节点，命名为username
    prosody = doc.createElement('prosody')
    prosody.appendChild(doc.createTextNode(voice.text))
    prosody.attributes['rate'] = "{}%".format(voice.rate)
    prosody.attributes['pitch'] = "{}%".format(voice.pitch)
    if voice.style:
        mstts = doc.createElement('mstts:express-as')
        mstts.attributes['style'] = voice.style
        voice_xml.appendChild(mstts)
        mstts.appendChild(prosody)
    else:
        voice_xml.appendChild(prosody)

    # with open('test.xml', 'wb') as fp:
    #     fp.write(doc.toprettyxml(encoding='utf-8'))
    xml = doc.toprettyxml(encoding='utf-8')
    xml = str(xml, 'utf-8')
    return xml


if __name__ == '__main__':
    voice = {
        'text': '我是谁，我是只能朗读机器人',
        'voice': 'zh-CN-XiaoxiaoNeural',
        'style': 'sad'
    }
    a = generate_xml_str(model.VoiceModel(**voice))
    print(a)
